package com.da.javatest.niuke.baodian;

/**
 * @author chenlida
 * @date 2020/10/17 21:41
 * https://www.nowcoder.com/practice/31a9495eb02844fb8c0e9ab101053f53?tpId=8&tags=&title=&diffculty=0&judgeStatus=0&rp=1
 */
public class C73Count2 {
    public static int countNumberOf2s(int n) {
        int count = 1;
        for (int i = 12; i <= n; i++) {
            int temp = i;
            while (temp > 0) {
                if (temp % 10 == 2) {
                    count++;
                }
                temp /= 10;
            }
        }
        return count;
    }

    public static int countNumberOf2s2(int n) {
        int count = 0;
        for (int i = 1; i <= n; i *= 10) {
            int a = n / i, b = n % i;
            //之所以补8，是因为当百位为0，则a/10==(a+8)/10，
            //当百位>=2，补8会产生进位位，效果等同于(a/10+1)
            count += (a + 7) / 10 * i + ((a % 10 == 2) ? b + 1 : 0);
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(countNumberOf2s(100));
        System.out.println(countNumberOf2s2(100));
    }

}
